<template>
  <el-dialog
    v-model="show"
    :title="isUpdate ? '修改属性' : '新增属性'"
    width="600px"
    destroy-on-close
    @close="closeModal"
  >
    <el-form ref="formRef" :model="form" label-width="80px">
      <el-form-item
        prop="AttrName"
        label="属性名称"
        required
        :rules="[{ message: '请输入属性名称', required: true }]"
      >
        <el-input
          v-model="form.AttrName"
          :disabled="isUpdate"
          placeholder="请输入属性名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="录入类型">
        <el-radio-group v-model="form.InputType">
          <el-radio
            v-for="(item, key) in inputTypeMap"
            :key="key"
            :value="Number(key)"
          >
            {{ item }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择列表" v-if="form.InputType == 0">
        <el-input
          v-if="form.AttrKeyName !== 'Settlement'"
          type="textarea"
          v-model="form.AttrValue"
          placeholder="请输入选择列表,逗号分隔"
          :rows="4"
          @change="handleSelectionChange"
        ></el-input>
        <!-- 从报价方式列表里取 -->
        <el-select
          v-else
          v-model="form.AttrValue"
          placeholder="请填选"
          multiple
        >
          <el-option
            v-for="(item, index) in offerList"
            :key="index"
            :label="item.AttrName"
            :value="item.AttrName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户输入" v-else>
        <el-radio-group v-model="form.InputType2">
          <el-radio
            v-for="(item, key) in inputModeMap"
            :key="key"
            :value="Number(key)"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="列固定">
        <el-radio-group v-model="form.FixType">
          <el-radio
            v-for="(item, key) in fixMap"
            :key="key"
            :value="Number(key)"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="列宽度">
        <el-input
          v-model.number="form.ColumnWidth"
          :disabled="form.autoCol"
          type="number"
          placeholder="请输入数字"
        >
        </el-input>
        <!-- <el-checkbox
          :checked="form.autoCol"
          label="自动分配宽度"
          @change="checkboxChange"
        ></el-checkbox> -->
      </el-form-item>
      <el-form-item
        label="默认值"
        v-if="form.InputType !== 2"
        prop="InputType"
        :rules="[{ validator: selectDefaultValid }]"
      >
        <template v-if="form.InputType == 0">
          <el-select
            v-model="form.DefaultValue"
            placeholder="设置默认值"
            clearable
            @focus="handleCheckValid"
          >
            <el-option
              v-for="item in formatSelectOption(form.AttrValue)"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </template>
        <template v-else>
          <el-input
            v-model="form.DefaultValue"
            placeholder="设置默认值"
          ></el-input>
        </template>
      </el-form-item>
      <el-form-item label="排序">
        <el-input
          v-model="form.SortIndex"
          class="w-20"
          type="number"
          placeholder=""
        ></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.IsVisible">
          <el-radio :value="true">显示</el-radio>
          <el-radio :value="false">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { reactive, toRef, toRefs, watch } from "vue";
import { errMsg } from "@/utils/errorMsg";
import {
  inputTypeMap,
  inputModeMap,
  orderAttrsMap,
  fixMap,
} from "../../../../../utils/map";
import { offerQueryApi } from "@/api/order/attr";
defineOptions({
  name: "DefaultEditModal",
});
const props = defineProps({
  open: {
    type: Boolean,
    required: true,
  },
  isUpdate: {
    type: Boolean,
    required: true,
  },
  data: {
    type: Object,
    required: true,
  },
});
const emits = defineEmits(["closeModal", "reload"]);

const state = reactive({
  form: {
    AttrName: "",
    AttrValue: "",
    InputType: 1,
    InputType2: 0,
    DefaultValue: "",
    selectOptions: "",
    ColumnWidth: 100,
    SortIndex: 0,
    IsVisible: true,
    FixType: 0,
    autoCol: false,
  },
  formRef: undefined,
  rules: {
    attrChar: [{ required: true, message: "请输入属性名称", trigger: "blur" }],
  },
  offerList: [],
});

const { form, formRef, rules, offerList } = toRefs(state);
watch(
  () => props.open,
  async (val) => {
    show.value = val;
    form.value = Object.assign(form.value, props.data);
    if (form.value.AttrValue instanceof Array) {
      form.value.AttrValue = form.value.AttrValue.join("，");
    }
    if (form.value.AttrKeyName == "Settlement") {
      form.value.AttrValue = form.value.AttrValue.split(",");
    }
    if (form.value.ColumnWidth == -1) form.value.autoCol = true;
    if (!props.isUpdate) {
      form.value = {
        SeriesId: props.data.SeriesId,
        AttrName: "",
        InputType: 1,
        DefaultValue: "",
        selectOptions: "",
        SortIndex: 0,
        InputType2: 0,
        ColumnWidth: 100,
        IsVisible: true,
        FixType: 0,
        autoCol: false,
      };
    }
    if (val) {
      const res = await offerQueryApi({ seriesId: form.value.SeriesId });
      offerList.value = res.Data || [];
    }
  }
);
const show = ref(false);

function closeModal() {
  show.value = false;
  emits("closeModal");
}

async function handleConfirm() {
  try {
    formRef.value.validate((valid) => {
      if (!valid) ElMessage.warning("请填写必填字段");
      // 接口请求
      else {
        form.value.AttrValue = formatSelectOption(form.value.AttrValue, true);
        if (props.isUpdate) {
          // form.value.DefaultValue = form.value.DefaultValue
          //   .replace(/，/g, ",")
          //   .split(",");
          emits("reload", form.value, true);
        } else {
          // form.value.DefaultValue = form.value.DefaultValue
          //   .replace(/，/g, ",")
          //   .split(",");
          form.value.AttrId = 0;
          emits("reload", form.value, false);
        }
        closeModal();
      }
    });
  } catch (error) {
    console.error("未知错误", error);
    // 请求失败处理
    ElMessage.error("修改失败：" + errMsg(error));
  }
}
function handleSelectionChange(val) {
  form.value.AttrValue = val;
  if (val) form.value.DefaultValue = "";
}
function selectDefaultValid(rule, value, callback) {
  if (!form.value.AttrValue && form.value.InputType == 0) {
    callback("请先填写列表项");
  }
  callback();
}
function handleCheckValid() {
  formRef.value.validateField("InputType", (res) => {});
}
function formatSelectOption(value, reflex) {
  if (reflex) {
    if (value instanceof Array) {
      return value.join(",");
    } else {
      return value;
    }
  } else {
    if (typeof value == "string") {
      return value.replace("，", ",").split(",").filter(Boolean);
    } else {
      return value;
    }
  }
}
function checkboxChange(val) {
  form.value.autoCol = val;
  if (val) form.value.ColumnWidth = -1;
  else form.value.ColumnWidth = 0;
}
</script>
<style lang="scss"></style>